<script setup lang="ts">
  import { ref } from 'vue'
  import { useGetInfoByCode } from '@/services/pages/code'
  import SelectGood from './select-good/index.vue'
  import useGoods from './useGoods'
  import { TableDataGoodInfoOrderCreate } from './types'
  import { HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import SelectChild from './select-child/SelectChild.vue'
  import { getTreeBySn } from '@/api/code'
  import { useRouter } from 'vue-router'

  const { codeInfo, getInfoLoading, getInfo } = useGetInfoByCode()
  const {
    goods,
    addGood,
    findGood,
    removeGood,
    clearAllGoods,
    clearAllNoRegisterCodes,
    clearAllRegisterCodes,
  } = useGoods()

  defineOptions({
    name: 'GoodInfoOrderCreate',
  })

  const props = defineProps({
    factoryId: {
      type: String,
      default: () => '',
    },
    userId: {
      type: String,
      default: () => '',
    },
  })

  const emits = defineEmits<{
    (e: 'change-goods'): void
    (e: 'change-user', value: CodeInfoByCode): void
  }>()

  const router = useRouter()

  // 合格证，用于搜索，带出对应的商品信息和客户信息
  const snCode = ref('')

  // 选择设备弹窗显示状态
  const selectGoodDialogVisible = ref(false)

  // 表格合格证搜索加载
  const getGoodAndUserInfoByCodeLoading = ref(false)

  const getForm = (data) => {
    return {
      code: data.securityCode,
      goodsName: data.name,
      goodsCode: '',
      goodsSpecName: data.specName,
      goodsBrand: '',
      qty: 1,
      img: '',
      buyTime: '',
      name: '',
      phone: '',
      province: '',
      city: '',
      area: '',
      town: '',
      address: '',
      isEmptyLine: false,
      type: data.codeUserRegister ? 1 : 2,
      goodId: data.id,
      goodSpecId: data.specId,
      codeId: data.codeId,
      goodsSpecCode: data.goodCode,
      parentName: '',
      warrantyStartTime: data.warrantyStartTime,
      warrantyEndTime: data.warrantyEndTime,
    }
  }

  const onGetProductAndCustomerInfoByCode = async () => {
    if (!snCode.value) {
      return
    }
    getGoodAndUserInfoByCodeLoading.value = true
    const res = await getTreeBySn(snCode.value)
    await getInfo(snCode.value)
    getGoodAndUserInfoByCodeLoading.value = false
    // await getInfo(snCode.value)
    const data = res.data.data

    if (data && data.id) {
      // const good = findGood(codeInfo.value.goodsId, codeInfo.value.goodsSpecId, codeInfo.value.code)
      // if (good) {
      //   HMessageBox.error(infoTip.order.create.goodIsExist)
      //   return
      // }
      if (data.type == 1) {
        const list = data.child.map((item) => {
          const obj = getForm(item)
          obj.parentName = data.name
          return obj
        })
        childRef.value.open({ list })
      } else {
        const form: any = getForm(data.child[0])
        form.parentName = data.name
        addGood(form)
      }
      emits('change-goods')
      snCode.value = ''
    } else {
      if (codeInfo.value) {
        const good = findGood(
          codeInfo.value.goodsId,
          codeInfo.value.goodsSpecId,
          codeInfo.value.code,
        )
        if (good) {
          HMessageBox.error(infoTip.order.create.goodIsExist)
          return
        }
        addGood({
          contractNo: codeInfo.value.contractNo || '',
          code: codeInfo.value.code,
          goodsName: codeInfo.value.goodsName,
          goodsSpecName: codeInfo.value.goodsSpecName,
          goodsBrand: codeInfo.value.goodsBrand,
          qty: 1,
          img: '',
          buyTime: '',
          name: codeInfo.value.name || '',
          phone: codeInfo.value.phone || '',
          province: codeInfo.value.province || '',
          city: codeInfo.value.city || '',
          area: codeInfo.value.area || '',
          town: codeInfo.value.town || '',
          address: codeInfo.value.address || '',
          isEmptyLine: false,
          type: codeInfo.value.userId ? 1 : 2,
          goodId: codeInfo.value.goodsId,
          goodSpecId: codeInfo.value.goodsSpecId,
          codeId: codeInfo.value.id,
          goodsSpecCode: codeInfo.value.goodsCode,
          warrantyEndTime: codeInfo.value.warrantyEndTime || '',
          warrantyStartTime: codeInfo.value.warrantyStartTime || '',
          buyMarket: '',
          dl: codeInfo.value.dl || '',
          specialBz: codeInfo.value.specialBz || '',
          standard: codeInfo.value.standard || '',
          voltage: codeInfo.value.voltage || '',
          xlh: codeInfo.value.xlh || '',
          tableType: codeInfo.value.tableType,
        })
        emits('change-goods')
        snCode.value = ''
      } else {
        HMessageBox.error(infoTip.order.create.noGetCodeInfoByCode)
      }
    }
    emits('change-user', codeInfo.value)
  }

  /**
   * 数量修改事件
   * @param index - 商品索引
   */
  const handleChangeQty = (index: number) => {
    if (goods.value[index].qty <= 0) {
      goods.value[index].qty = 1
    }
  }

  /**
   * 商品删除事件
   * @param goodsId - 商品id
   * @param goodSpecId - 商品规格id
   * @param code - 合格证
   */
  const deleteGoods = (goodsId: string, goodSpecId: string, code: string) => {
    removeGood(goodsId, goodSpecId, code)
    emits('change-goods')
  }

  /**
   * 获取表格行索引，用于给搜索行固定
   * @param data - 事件回调参数
   */
  const getRowClassName = (data: { row: TableDataGoodInfoOrderCreate; rowIndex: number }) => {
    if (data.rowIndex === 0) {
      return 'fixed-row'
    }
  }

  const childRef = ref()
  const childConfirm = (data) => {
    data.forEach((item) => {
      addGood(item)
      emits('change-goods')
    })
  }

  const handleCodeClick = (good: TableDataGoodInfoOrderCreate) => {
    router.push(`/code/codetail/${good.codeId}/${good.tableType}`)
  }

  defineExpose({
    addGood,
    getGoods: () => {
      const result: Array<OrderAPIRequest.OrderCreateFormGoodListItem> = []

      const goodList = goods.value.filter((good) => good.type === 3)
      const registeredCodeList = goods.value.filter((good) => good.type === 1)
      const noRegisterCodeList = goods.value.filter((good) => good.type === 2)

      if (
        goodList.length === 0 &&
        registeredCodeList.length === 0 &&
        noRegisterCodeList.length === 0
      ) {
        return []
      }

      if (registeredCodeList.length > 0) {
        const obj: OrderAPIRequest.OrderCreateFormGoodListItem = {
          type: 1,
          orderGoodsVos: [],
        }
        registeredCodeList.forEach((registeredCode) => {
          if (registeredCode.goodId && registeredCode.goodSpecId) {
            obj.orderGoodsVos.push({
              buyTime: registeredCode.buyTime,
              codeIds: [registeredCode.codeId],
              endTime: '',
              goodsId: registeredCode.goodId,
              goodsSpecId: registeredCode.goodSpecId,
              id: '',
              qty: registeredCode.qty,
              buyMarket: registeredCode.buyMarket,
              dl: registeredCode.dl,
              specialBz: registeredCode.specialBz,
              standard: registeredCode.standard,
              voltage: registeredCode.voltage,
              xlh: registeredCode.xlh,
            })
          }
        })
        result.push(obj)
      }

      if (noRegisterCodeList.length > 0) {
        const obj: OrderAPIRequest.OrderCreateFormGoodListItem = {
          type: 2,
          orderGoodsVos: [],
        }

        noRegisterCodeList.forEach((noRegisterCode) => {
          if (noRegisterCode.goodId && noRegisterCode.goodSpecId) {
            obj.orderGoodsVos.push({
              buyTime: noRegisterCode.buyTime,
              codeIds: [noRegisterCode.codeId],
              endTime: '',
              goodsId: noRegisterCode.goodId,
              goodsSpecId: noRegisterCode.goodSpecId,
              id: '',
              qty: noRegisterCode.qty,
              buyMarket: noRegisterCode.buyMarket,
              dl: noRegisterCode.dl,
              specialBz: noRegisterCode.specialBz,
              standard: noRegisterCode.standard,
              voltage: noRegisterCode.voltage,
              xlh: noRegisterCode.xlh,
            })
          }
        })

        result.push(obj)
      }

      if (goodList.length > 0) {
        const obj: OrderAPIRequest.OrderCreateFormGoodListItem = {
          type: 3,
          orderGoodsVos: [],
        }

        goodList.forEach((good) => {
          if (good.goodId && good.goodSpecId) {
            obj.orderGoodsVos.push({
              buyTime: good.buyTime,
              codeIds: [],
              endTime: '',
              goodsId: good.goodId,
              goodsSpecId: good.goodSpecId,
              id: '',
              qty: good.qty,
              buyMarket: good.buyMarket,
              dl: good.dl,
              specialBz: good.specialBz,
              standard: good.standard,
              voltage: good.voltage,
              xlh: good.xlh,
            })
          }
        })

        result.push(obj)
      }

      return result
    },
    clear: () => {
      clearAllGoods()
      clearAllNoRegisterCodes()
      clearAllRegisterCodes()
    },
  })
</script>

<template>
  <div v-loading="getInfoLoading" class="good-info-order-create">
    <div class="title">设备列表</div>
    <el-table
      :border="true"
      stripe
      :data="goods"
      scrollbar-always-on
      max-height="350"
      :row-class-name="getRowClassName"
    >
      <!-- 序号 -->
      <el-table-column type="index" width="50" fixed="left" :align="'center'" label="序号" />

      <!-- 合格证 -->
      <el-table-column label="合格证" show-overflow-tooltip width="240" fixed="left">
        <template #default="{ row }">
          <div v-if="row.isEmptyLine">
            <el-input
              v-model.trim="snCode"
              class="sn-code-input"
              placeholder="请输入合格证"
              clearable
              @keyup.enter="onGetProductAndCustomerInfoByCode"
            />
            <h-button
              type="primary"
              :loading="getGoodAndUserInfoByCodeLoading"
              @click="onGetProductAndCustomerInfoByCode"
            >
              搜索并添加
            </h-button>
          </div>
          <h-link v-else @click="handleCodeClick(row)">{{ row.code }}</h-link>
        </template>
      </el-table-column>

      <!-- 合同号 -->
      <el-table-column label="合同号" show-overflow-tooltip width="140">
        <template #default="{ row }">
          {{ row.isEmptyLine ? '' : row.contractNo }}
        </template>
      </el-table-column>

      <!-- 合同号 -->
      <!-- <el-table-column label="合同号" show-overflow-tooltip width="140">
        <template #default="{ row }">
          {{ row.isEmptyLine ? '' : row.contractNo }}
        </template>
      </el-table-column> -->
      <!-- <template #default="{ row }">
          <div v-if="row.isEmptyLine">
            <el-input
              v-model.trim="snCode"
              class="sn-code-input"
              placeholder="请输入合格证"
              clearable
              @keyup.enter="onGetProductAndCustomerInfoByCode"
            />
            <h-button
              type="primary"
              :loading="getGoodAndUserInfoByCodeLoading"
              @click="onGetProductAndCustomerInfoByCode"
              >搜索并添加</h-button
            >
          </div>
        </template> -->

      <!-- 物料编码 -->
      <el-table-column label="物料编码" width="120" prop="goodsSpecCode" show-overflow-tooltip />

      <!-- 物料名称 -->
      <el-table-column label="物料名称" width="140" prop="goodsName" show-overflow-tooltip />

      <!-- 规格型号 -->
      <el-table-column label="规格型号" width="140" prop="goodsSpecName" show-overflow-tooltip />

      <!-- 系列号 -->
      <!-- <el-table-column label="系列号" width="140" show-overflow-tooltip prop="xlh" /> -->

      <!-- 父项 -->
      <!-- <el-table-column
        label="父项"
        width="140"
        prop="parentName"
        show-overflow-tooltip
      ></el-table-column> -->

      <!-- 数量 -->
      <el-table-column label="数量" width="80">
        <template #default="{ row, $index }">
          <template v-if="!row.isEmptyLine">
            <el-input
              v-if="row.type === 3"
              v-model.trim.number="row.qty"
              maxlength="5"
              @input="handleChangeQty($index)"
            />
            <el-input v-else v-model.trim="row.qty" disabled />
          </template>
        </template>
      </el-table-column>

      <!-- 电源电压（V） -->
      <!-- <el-table-column label="电源电压（V）" width="140" show-overflow-tooltip prop="voltage" /> -->

      <!-- 额定电流（V） -->
      <!-- <el-table-column label="额定电流（V）" width="140" show-overflow-tooltip prop="dl" /> -->

      <!-- 是否标准 -->
      <!-- <el-table-column label="标准" width="140" show-overflow-tooltip prop="standard" /> -->

      <!-- 特殊要求 -->
      <!-- <el-table-column label="特殊要求" width="140" show-overflow-tooltip prop="specialBz" /> -->

      <!-- 图片 -->
      <!-- <el-table-column label="图片" width="200">
        <template #default="{ row }">
          <div v-if="row.img" class="pic">
            <h-image
              :width="40"
              :height="25"
              :src="row.img || defaultImg"
              :padding="2"
              :show-del-btn="false"
            />
          </div>
        </template>
      </el-table-column> -->

      <!-- 购买时间 -->
      <!-- <el-table-column label="购买时间" width="170" prop="buyTime">
        <template #default="{ row }">
          <el-date-picker
            v-if="row.type !== 1 && row.type !== 0"
            v-model="row.buyTime"
            style="width: 140px"
            value-format="YYYY-MM-DD"
            type="date"
          ></el-date-picker>
        </template>
      </el-table-column> -->

      <!-- 是否带配件 -->
      <!-- <el-table-column label="是否带配件" width="140">
        <template #default="{ row }">
          <el-select v-if="!row.isEmptyLine">
            <el-option :value="1" label="凤凰端子" />
            <el-option :value="2" label="温湿度线" />
            <el-option :value="3" label="电源模块" />
            <el-option :value="4" label="说明书" />
            <el-option :value="5" label="出厂报告" />
            <el-option :value="6" label="其他配件" />
          </el-select>
        </template>
      </el-table-column> -->

      <!-- 质保开始 -->
      <el-table-column prop="warrantyStartTime" label="质保开始" width="128" />

      <!-- 质保截止 -->
      <el-table-column prop="warrantyEndTime" label="质保截止" width="128" />

      <!-- 登记信息 -->
      <el-table-column label="登记信息" min-width="360" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.name }}&nbsp;{{ row.phone }}&nbsp; {{ row.province }}-{{ row.city }}-{{
            row.area
          }}-{{ row.town }}-{{ row.address }}
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" fixed="right" width="75">
        <template #header>
          <h-link @click="selectGoodDialogVisible = true">选择设备</h-link>
        </template>

        <template #default="{ row }">
          <h-link
            v-if="!row.isEmptyLine"
            type="error"
            @click="deleteGoods(row.goodId, row.goodSpecId, row.code)"
          >
            删除
          </h-link>
        </template>
      </el-table-column>
    </el-table>

    <select-good
      v-model:visible="selectGoodDialogVisible"
      :factory-id="props.factoryId"
      :user-id="props.userId"
      @change-goods="emits('change-goods')"
    />
    <select-child ref="childRef" @confirm="childConfirm" />
  </div>
</template>

<style scoped lang="scss">
  :deep(.fixed-row) {
    position: sticky;
    position: -webkit-sticky;
    top: 0;
    z-index: 3;
  }

  .sn-code-input {
    width: 120px;
    margin-right: 5px;
  }

  .good-info-order-create {
    box-sizing: border-box;
    padding: 0 12px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    row-gap: 5px;
    height: 100%;

    .title {
      padding-left: 6px;
      border-left: 3px solid $primaryColor;
      font-size: 14px;
      font-weight: bold;
    }
  }

  :deep(.el-table__body-wrapper) {
    .el-scrollbar {
      .el-scrollbar__wrap {
        box-sizing: border-box;
        padding-bottom: 13px;
      }
    }
  }
</style>
